package com.ziyuan.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ziyuan.pojo.Result;
import com.ziyuan.pojo.User;
import com.ziyuan.service.Userservice;
import com.ziyuan.utils.Md5Util;
import com.ziyuan.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class Usercontroller {
    @Autowired
    private Userservice userservice;

    @PostMapping("/register")
    public Result zhuce(@Pattern(regexp = "^[a-zA-Z0-9]{5,12}$") String username,
                        @Pattern(regexp = "^[a-zA-Z0-9]{5,12}$") String password) {
//        判断用户是否存在
        User findByUserName = userservice.FindByUserName(username);
        if (findByUserName.getUsername() == null) {
// 进行注册
            userservice.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名重复");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^[a-zA-Z0-9]{5,12}$") String username,
                        @Pattern(regexp = "^[a-zA-Z0-9]{5,12}$") String password) throws JsonProcessingException {
        User user = userservice.FindByUserName(username);
        log.info("用户名和密码分别为：{},{}", username, password);
//        用户不存在
        if (user.getUsername() == null) {
            return Result.success("用户不存在");

        }
        log.info("加密的：{}，数据库的：{}",Md5Util.getMD5String(password),user.getPassword());
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            Map<String,Object> claimsss = new HashMap<>();
            claimsss.put("username",user.getUsername());
            claimsss.put("id",user.getId());
            String token1 = JWTUtil.createToken(claimsss, "claims".getBytes());
//            String token = JwtUtil.genToken(claimsss);
            return Result.success(token1);
        }
        return Result.error("密码错误");

    }
    @GetMapping("/userInfo")
    public Result userinfo(@RequestHeader(name = "Authorization") String string) throws JsonProcessingException {
//        Map<String, Object> stringObjectMap = JwtUtil.parseToken(string);
//        JWT jwt = JWTUtil.parseToken(string);
//        JWTPayload payload = jwt.getPayload();

//        log.info("糊涂包的名字是：{}",username1);
        log.info("token参数为：{}",string);
//        String username = (String) stringObjectMap.get("username");
        Map<String,String> o1 = ThreadLocalUtil.get();
//        Map<String,String> o1 = ThreadLocalUtil.get();
//        JWTPayload payload1 = o.getPayload();
        String username1 = o1.get("username");
//        String username1 = (String) payload1.getClaim("username");
        User user = userservice.FindByUserName(username1);
        return Result.success(user);
    }
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userservice.update(user);
        return Result.success();
    }
    @PatchMapping("/updateAvatar")
    public Result image(@RequestParam @URL String avatarUrl){
        userservice.image(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map){
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
//        判断三个密码是否为空
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("参数有错误");
        }
//        判断旧密码
        Map<String,String>  o = ThreadLocalUtil.get();
        String username = o.get("username");
        String password = userservice.FindByUserName(username).getPassword();
        log.info("输入旧密码为{}，数据库密码为{}",Md5Util.getMD5String(oldPwd),password);
        if (!password.equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("旧密码与新密码不符合");
        }
//        判断两个新密码
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码输入不一致");
        }
        String md5String = Md5Util.getMD5String(newPwd);
        userservice.updatepwd(md5String,username);
        return Result.success();
    }

}
